//-----------------------------------------------------------------------------
//  Copyright (C) 2005-2008 Thomas S. Ullrich 
//
//  This file is part of the Solitaire Mahjong project.
//
//  This file may be used under the terms of the GNU General Public License.
//  This project is free software; you can redistribute it and/or modify it
//  under the terms of the GNU General Public License.
//  
//  Author: Thomas S. Ullrich
//  Last update: June 1, 2007
//-----------------------------------------------------------------------------
#include "smHighscoreEntry.h"
 
smHighscoreEntry::smHighscoreEntry()
    : mStartTime(0), mEndTime(0),
      mTiles(0), mHints(0), mUndos(0)
{ /* noop */ }
 
smHighscoreEntry::smHighscoreEntry(time_t start, time_t end,
                                   unsigned int tiles, unsigned int hints,
                                   unsigned int undos)
    : mStartTime(start), mEndTime(end),
      mTiles(tiles), mHints(hints), mUndos(undos)
{ /* noop */ }
 
bool smHighscoreEntry::isValid() const
{
    if (mStartTime && mEndTime && mEndTime >= mStartTime)
        return true;
    else
        return false;
}
 
time_t smHighscoreEntry::deltaTime() const
{
    return mEndTime-mStartTime+1;
}
 
QString smHighscoreEntry::date() const
{
    QString theDate = ctime(&mEndTime);
    theDate.remove('\n');
    return theDate;
}
 
QString smHighscoreEntry::tiles() const
{
    QString theTiles;
    theTiles.setNum(mTiles);
    return theTiles;
}
 
QString smHighscoreEntry::hints() const
{
    QString theHints;
    theHints.setNum(mHints);
    return theHints;
}
 
QString smHighscoreEntry::undos() const
{
    QString theUndos;
    theUndos.setNum(mUndos);
    return theUndos;
}
 
QString smHighscoreEntry::duration() const
{
    time_t d = deltaTime();
    int m = d/60;
    int s = d%60;
    char text[8];
    sprintf(text, "%02d:%02d", m, s);
    return QString(text);
}
 
bool smHighscoreEntryCompare::operator()(smHighscoreEntry a, smHighscoreEntry b) const
{
    // operator < or return true if "a" is a higher score than "b"
    // This coukld be written more compact but it's easier to read
    // and change.
     
    //
    //  First criterium: # of tiles left
    //  Second criterium: # of hints
    //  Third criterium: # of undos
    //  Fourth criterium: time played
    //
    if (a.mTiles < b.mTiles)
        return true;
    else if (a.mTiles == b.mTiles) {
        if (a.mHints < b.mHints)
            return true;
        else if (a.mHints == b.mHints) {
            if (a.mUndos < b.mUndos)
                return true;
            else if (a.mUndos == b.mUndos) {
                if (a.deltaTime() < b.deltaTime())
                    return true;
            }
        }
    }
    return false;
}
 
ostream& operator<<(ostream& os, const smHighscoreEntry& e)
{
    os << static_cast<const char*>(e.date().toAscii()) 
       << '\t' << e.mTiles << '\t' << e.mHints 
       << '\t' << e.mUndos << '\t' << e.deltaTime();
    return os;
}
